#!/usr/bin/env python3
# coding: utf-8
"""
2024-02-04 harrydeep@wardyan.top 
主数据库暂时只支持mssql
"""
## import os
import pymssql
import pymysql
#import threading
from DBUtils.PooledDB import PooledDB
# from dbutils.pooled_db import PooledDB          #, SharedDBConnection
## from wconfig.Config import *
## from aaaaaaaa import *
## from myconfig import *
## import WConfig
import os
import configparser
from loguru import logger
from config import Config
from top.wardyan.core.utils.common import *

## 主数据源
MAINCONFIG = "main"


"""
POOL = PooledDB(
    creator=pymssql,  # 使用链接数据库的模块
    maxconnections=Config.getconfig_int("db","maxconnections"),  # 连接池允许的最大连接数，0和None表示不限制连接数
    mincached=Config.getconfig_int("db","mincached"),  # 初始化时，链接池中至少创建的空闲的链接，0表示不创建
    maxcached=Config.getconfig_int("db","maxcached"),  # 链接池中最多闲置的链接，0和None不限制
    maxshared=Config.getconfig_int("db","maxshared"),  # 链接池中最多共享的链接数量，0和None表示全部共享。PS: 无用，因为pymysql和MySQLdb等模块的 threadsafety都为1，所有值无论设置为多少，_maxcached永远为0，所以永远是所有链接都共享。
    blocking=Config.getconfig_bool("db","blocking"),  # 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错
    maxusage=Config.getconfig_int("db","maxusage"),  # 一个链接最多被重复使用的次数，None表示无限制
    setsession=[""],  # 开始会话前执行的命令列表。如：["set datestyle to ...", "set time zone ..."]set rowcount 10000
    ping=0,
    # ping MySQL服务端，检查是否服务可用。# 如：0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
    host=Config.getconfig("db","host"),
    port=Config.getconfig("db","port"),
    user=Config.getconfig("db","user"),
    password=Config.getconfig("db","password"),
    database=Config.getconfig("db","database"),
    charset='utf8'
)
"""
def _connect_db_pools (host : str, port : int, user : str, password : str, database : str
    , creator = pymssql
    , maxconnections : int = 0
    , mincached : int = 0
    , maxcached : int = 0
    , maxshared : int = 0
    , blocking : bool = True
    , maxusage : int = 0
    , charset : str = "utf8"
) -> PooledDB:
    """
    连接数据库.
    host  \n
    port  \n
    user  \n
    password  \n
    database  \n
    creator 使用链接数据库的模块 \n
    maxconnections 连接池允许的最大连接数，0和None表示不限制连接数  \n
    mincached 初始化时，链接池中至少创建的空闲的链接，0表示不创建  \n
    maxcached 链接池中最多闲置的链接，0和None不限制  \n
    maxshared  链接池中最多共享的链接数量，0和None表示全部共享。PS: 无用，因为pymysql和MySQLdb等模块的 threadsafety都为1，所有值无论设置为多少，_maxcached永远为0，所以永远是所有链接都共享。  \n
    blocking 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错  \n
    maxusage 一个链接最多被重复使用的次数，None表示无限制  \n
    """
    return PooledDB(
        creator=creator,  # 使用链接数据库的模块
        maxconnections=maxconnections,  # 连接池允许的最大连接数，0和None表示不限制连接数
        mincached=mincached,  # 初始化时，链接池中至少创建的空闲的链接，0表示不创建
        maxcached=maxcached,  # 链接池中最多闲置的链接，0和None不限制
        maxshared=maxshared,  # 链接池中最多共享的链接数量，0和None表示全部共享。PS: 无用，因为pymysql和MySQLdb等模块的 threadsafety都为1，所有值无论设置为多少，_maxcached永远为0，所以永远是所有链接都共享。
        blocking=blocking,  # 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错
        maxusage=maxusage,  # 一个链接最多被重复使用的次数，None表示无限制
        setsession=[""],  # 开始会话前执行的命令列表。如：["set datestyle to ...", "set time zone ..."]set rowcount 10000
        ping=0,
        # ping MySQL服务端，检查是否服务可用。# 如：0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
        host=host,
        port=port,
        user=user,
        password=password,
        database=database,
        charset=charset,
        ## cursorclass=pymssql.cursors.DictCursor
    )
    


DBCONFIGS = {}

## 首先是主数据源
## 主数据源的配置名一律是main,没有指定use时一律以main主数据源为准
host = Config.getconfig("db","host") or ""
port = Config.getconfig_int("db","port")
user = Config.getconfig("db","user") or ""
password = Config.getconfig("db","password") or ""
database = Config.getconfig("db","database") or ""
maxconnections = Config.getconfig_int("db","maxconnections")
mincached = Config.getconfig_int("db","mincached")
maxcached = Config.getconfig_int("db","maxcached")
maxshared = Config.getconfig_int("db","maxshared")
blocking = Config.getconfig_bool("db","blocking")
maxusage = Config.getconfig_int("db","maxusage")
charset = Config.getconfig("db","charset") or "utf8"


## 如果通过配置工具配置的(密码可能已加密)
# 判断config目录下有没有dbconfig.ini文件，如果有，则读取配置文件
_config_file_name_ = "config\\dbconfig.ini"
if os.path.exists(_config_file_name_) :
    #Config.config.read(_config_file_name_)
    # 强制从dbconfig.ini读取配置
    db_config = configparser.ConfigParser()
    db_config.read(_config_file_name_, encoding="utf-8")
    
    if db_config.has_section("db"):
        if db_config.has_option("db", "host"):
            host = db_config.get("db", "host") or ""
        if db_config.has_option("db", "port"):
            try:
                port = db_config.getint("db", "port")
            except:
                port = 1433
        if db_config.has_option("db", "user"):
            user = db_config.get("db", "user") or ""
        if db_config.has_option("db", "password"):
            password = db_config.get("db", "password") or ""
        if db_config.has_option("db", "database"):
            database = db_config.get("db", "database") or ""
        if db_config.has_option("db", "maxconnections"):
            try:
                maxconnections = db_config.getint("db", "maxconnections")
            except:
                maxconnections = 0
        if db_config.has_option("db", "mincached"):
            try:
                mincached = db_config.getint("db", "mincached")
            except:
                mincached = 1
        if db_config.has_option("db", "maxcached"):
            try:
                maxcached = db_config.getint("db", "maxcached")
            except:
                maxcached = 5
        if db_config.has_option("db", "maxshared"):
            try:
                maxshared = db_config.getint("db", "maxshared")
            except:
                maxshared = 0
        if db_config.has_option("db", "blocking"):
            try:
                blocking = db_config.getboolean("db", "blocking")
            except:
                blocking = True
        if db_config.has_option("db", "maxusage"):
            try:
                maxusage = db_config.getint("db", "maxusage")
            except:
                maxusage = 0
        if db_config.has_option("db", "charset"):
            charset = db_config.get("db", "charset") or "utf8"
        
print(current_timestamp(), "连接数据库:", "host=" ,host, "port=",port, "user=",user, "database=",database)
POOL = _connect_db_pools(host=host, port=port, user=user,password=password,database=database,creator=pymssql,maxconnections=maxconnections,mincached=mincached,maxcached=maxcached,maxshared=maxshared,blocking=blocking,maxusage=maxusage,charset=charset)
DBCONFIGS[MAINCONFIG]=POOL
print(current_timestamp(), "连接数据库 - 完成:", "host=" ,host, "port=",port, "user=",user, "database=",database)

## 其次是附加数据源
if Config.config.cfg.has_option("db","exts") :
    cfgs = Config.getconfig("db","exts")
    if cfgs is not None and len(cfgs) > 0 :
        cs = cfgs.split((",")) if cfgs else []
        for c in cs :
            ## c 每个配置名
            try :
                if Config.config.cfg.has_section(c) :
                    host = Config.getconfig(c,"host") or ""
                    port = Config.getconfig_int(c,"port")
                    user = Config.getconfig(c,"user") or ""
                    password = Config.getconfig(c,"password") or ""
                    database = Config.getconfig(c,"database") or ""

                    maxconnections = 0
                    mincached = 0
                    maxcached = 0
                    maxshared = 0
                    blocking = True
                    maxusage = 0
                    charset = "utf8"
                    type = pymssql
                    t = ""
                    if Config.config.cfg.has_option(c, "maxconnections") :
                        maxconnections = Config.getconfig_int(c,"maxconnections")
                    if Config.config.cfg.has_option(c, "mincached") :
                        mincached = Config.getconfig_int(c,"mincached")                        
                    if Config.config.cfg.has_option(c, "maxcached") :
                        maxcached = Config.getconfig_int(c,"maxcached")
                    if Config.config.cfg.has_option(c, "maxshared") :
                        maxshared = Config.getconfig_int(c,"maxshared")
                    if Config.config.cfg.has_option(c, "blocking") :
                        blocking = Config.getconfig_bool(c,"blocking")
                    if Config.config.cfg.has_option(c, "maxusage") :
                        maxusage = Config.getconfig_int(c,"maxusage")
                    if Config.config.cfg.has_option(c, "charset") :
                        charset = Config.getconfig_str(c,"charset") or "utf8"
                    if Config.config.cfg.has_option(c, "type") :
                        t = Config.getconfig(c,"type") or ""
                    if t and len(t) > 0 :
                        if t == "pymysql" :
                            type = pymysql
                    if host and len(host) > 0 and port and port > 0 and user and len(user) > 0 and database and len(database) > 0 :
                        print(current_timestamp(), "连接数据库:", "host=" ,host, "port=",port, "user=",user, "database=",database)
                        p = _connect_db_pools(host=host, port=port, user=user,password=password,database=database,creator=type,maxconnections=maxconnections,mincached=mincached,maxcached=maxcached,maxshared=maxshared,blocking=blocking,maxusage=maxusage,charset=charset)
                        DBCONFIGS[c]=p
                        print(current_timestamp(), "连接数据库 - 完成:", "host=" ,host, "port=",port, "user=",user, "database=",database)
                else :
                    logger.warning("配置不存在:" + c)
            except BaseException as e :
                logger.warning(e)

## 日志框架
if __name__ == '__main__':
    ## db = POOL.connection()
    db = DBCONFIGS["main"].connection()
    cursor = db.cursor()
    
    cursor.execute("select * from kt_device")
    ## print(cursor.fetchall())
    cursor.close()
    db.close()


    
    db = DBCONFIGS["ERPDB"].connection()
    cursor = db.cursor()
    
    cursor.execute("select * from kt_device")
    print(cursor.fetchall())
    cursor.close()
    db.close()